package com.gjp.etfweb.utils;

import com.gjp.etfweb.common.Constant;
import org.springframework.util.StringUtils;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

public class HttpsUtils {

    public static String httpsRequest(String requestUrl) throws IOException, KeyManagementException, NoSuchProviderException, NoSuchAlgorithmException {
        Map<String, String> requestPropertyMap = Constant.getRequestPropertyMap();
        return httpsRequest(requestUrl, requestPropertyMap, "utf-8");
    }

    public static String httpsRequest(String requestUrl, String charset) throws IOException, KeyManagementException, NoSuchProviderException, NoSuchAlgorithmException {
        //设置请求头
        Map<String, String> requestPropertyMap = Constant.getRequestPropertyMap();
        return httpsRequest(requestUrl, requestPropertyMap, charset);
    }

    public static String httpsRequest(String requestUrl, Map<String, String> requestPropertyMap, String charset) throws IOException, KeyManagementException, NoSuchProviderException, NoSuchAlgorithmException {
        return httpsRequest(requestUrl, "GET", requestPropertyMap, charset);
    }

    public static String httpsRequest(String requestUrl, String requestMethod, Map<String, String> requestPropertyMap, String charset) throws IOException, KeyManagementException, NoSuchProviderException, NoSuchAlgorithmException {
        StringBuffer buffer = new StringBuffer();
        BufferedReader bufferedReader = null;
        HttpsURLConnection httpsUrlConn = null;

        // 建立并向网页发送请求
        try {
            //获取http链接
            httpsUrlConn = HttpsUtils.getProxyConnection(requestUrl);
            //设置请求头
            for (String key : requestPropertyMap.keySet()) {
                httpsUrlConn.setRequestProperty(key, requestPropertyMap.get(key));
            }
            //防止报403错误。
            httpsUrlConn.setDoOutput(true);
            httpsUrlConn.setDoInput(true);
            httpsUrlConn.setUseCaches(false);
            httpsUrlConn.setConnectTimeout(15000);
            httpsUrlConn.setReadTimeout(15000);
            // 请求的类型
            httpsUrlConn.setRequestMethod(requestMethod);
            //发起连接
            httpsUrlConn.connect();

            // 定义 BufferedReader输入流来读取URL的响应
            if (httpsUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK
                    || httpsUrlConn.getResponseCode() == HttpURLConnection.HTTP_CREATED
                    || httpsUrlConn.getResponseCode() == HttpURLConnection.HTTP_ACCEPTED) {
                bufferedReader = new BufferedReader(new InputStreamReader(httpsUrlConn.getInputStream(), charset));
            } else {
                bufferedReader = new BufferedReader(new InputStreamReader(httpsUrlConn.getErrorStream(), charset));
            }

            // 从输入流读取结果
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
        } catch (IOException | NoSuchAlgorithmException | NoSuchProviderException | KeyManagementException e) {
            throw e;
        } finally {
            // 释放资源
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpsUrlConn != null) {
                httpsUrlConn.disconnect();
            }
        }
        return buffer.toString();
    }

    public static HttpsURLConnection getProxyConnection(String requestUrl) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
        URL url = new URL(requestUrl);
        HttpsURLConnection httpUrlConn;
        if (Constant.PROXY_OPEN) {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(Constant.PROXY_HOST, Constant.PROXY_PORT));
            httpUrlConn = (HttpsURLConnection) url.openConnection(proxy);
        } else {
            httpUrlConn = (HttpsURLConnection) url.openConnection();
        }
        //设置安全socket
        httpUrlConn.setSSLSocketFactory(HttpsUtils.getSSLSocketFactory());
        return httpUrlConn;
    }

    public static SSLSocketFactory getSSLSocketFactory() throws NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException {
        TrustManager[] tm = {new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        }};

        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        // 从上述SSLContext对象中得到SSLSocketFactory对象
        return sslContext.getSocketFactory();
    }

    public static String get(String apiUrl) {
        String responseText = "";
        while (StringUtils.isEmpty(responseText)) {
            try {
                responseText = httpsRequest(apiUrl);
            } catch (Exception ignored) {
            }
        }
        return responseText;
    }
}
